import json
import re

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.user.models import User


class UsernameCountView(View):
    def get(self, request, username):
        # 1.接收用户名
        print(username)
        # 2.根据用户名查数据库
        count = User.objects.filter(username=username).count()
        # 返回响应
        return JsonResponse({'count': count, 'code': '0', 'errmsg': 'ok'})


class RegisterView(View):
    def post(self, request):
        # 步骤
        # 1.接收请求
        body_byte = request.body
        # 获取json格式数据转为字典
        body_dict = json.loads(body_byte)
        # 2.获取数据
        username = body_dict.get('username')
        password = body_dict.get('password')
        password2 = body_dict.get('password2')
        mobile = body_dict.get('mobile')
        sms_code = body_dict.get('sms_code')
        allow = body_dict.get('allow')
        # 3.验证数据
        # 3.1验证是否为空 有没有传
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({'code': '400', 'errmsg': 'register fail'})

        # 3.2正则验证
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({'code': '400', 'errmsg': 'register fail'})
        # 4.生成用户报错到数据库
        # user = User(username=username, password=password, mobile=mobile)
        # user.save()
        # 密码加密
        User.objects.create_user(username=username, password=password, mobile=mobile)
        # 5.返回响应
        return HttpResponse({'code': '0', 'errmsg': 'ok'})
